﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Configuration;

namespace Mammoo.File
{
    public static class FileHelper
    {
        /// <summary>
        /// 上传文件(可以在Web.config的appSettings添加MAX_UPLOAD_FILE来限制上传文件的大小)
        /// </summary>
        /// <param name="hpf">HttpPostFile</param>
        /// <param name="fileTypes">验证上传的文件类型,例:rar|txt|jpg</param>
        /// <param name="savePath">保存到服务器的相对路径</param>
        /// <param name="newFileName">返回上传后文件的新名字</param>
        /// <returns>0,上传失败;1,上传成功;2,文件为空;3,错误的文件格式;4,新建文件夹失败;5,上传文件超过最大长度.</returns>
        public static int Upload(HttpPostedFile hpf, string fileTypes, string savePath, out string newFileName)
        {
            newFileName = string.Empty;

            if (hpf == null || hpf.ContentLength <= 0)
            {
                return 2; //文件为空
            }

            int maxFileLength = 0;
            try
            {
                maxFileLength = Convert.ToInt32(ConfigurationManager.AppSettings["MAX_UPLOAD_FILE"].ToString());

                if (hpf.ContentLength > maxFileLength)
                {
                    return 5; //上传文件超过最大长度
                }
            }
            catch
            {

            }

            string fileName = hpf.FileName;
            string fileType = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();

            if (fileTypes.Length >= 0 && fileTypes.IndexOf(fileType) < 0)
            {
                return 3; //错误的文件的格式
            }

            newFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + "." + fileType;

            string filePath = savePath + "/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";

            string phyPath = HttpContext.Current.Request.MapPath(filePath);

            try
            {
                //判断路径是否存在,若不存在则创建路径
                DirectoryInfo upDir = new DirectoryInfo(phyPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
            }
            catch
            {
                return 4; //新建文件夹失败
            }

            try
            {
                hpf.SaveAs(HttpContext.Current.Request.MapPath(filePath) + newFileName);

            }
            catch
            {
                return 0; //上传失败
            }

            return 1; //上传成功
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath">文件相对路径</param>
        public static void DownLoad(string filePath)
        {
            filePath = HttpContext.Current.Server.MapPath(filePath);
            string saveFileName = "";
            int intStart = filePath.LastIndexOf("\\") + 1;
            saveFileName = filePath.Substring(intStart, filePath.Length - intStart);
            FileStream MyFileStream;
            long FileSize;

            if (System.IO.File.Exists(filePath))
            {
                MyFileStream = new FileStream(filePath, FileMode.Open);
                FileSize = MyFileStream.Length;

                byte[] Buffer = new byte[(int)FileSize];
                MyFileStream.Read(Buffer, 0, (int)FileSize);
                MyFileStream.Close();

                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + saveFileName);
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                HttpContext.Current.Response.ContentType = "application/x-download";

                HttpContext.Current.Response.BinaryWrite(Buffer);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Close();
                HttpContext.Current.Response.End();
            }
            else
            {
                HttpContext.Current.Response.Write("<script>alert(\"文件下载失败，该文件不存在！\");window.open('','_self');window.close();</script>");
            }
        }
    }
}
